<template>
  <div style="display: flex; flex: 1">
    <TableWidget
      v-if="hasData"
      ref="refTable"
      :pagination="pagination"
      :columns="columns"
      :load="onLoadAssets"
      :has-select="false"
      :hide-pageable="false"
      style="flex: 1"
      :show-zebra="true"
      :show-column="true"
      :show-refresh="false"
    >
      <template v-slot:toolHeader>
        <TableSearchWidget ref="refSearch" :search="searchParams">
          <template v-slot:searchTail>
            <div style="display: flex; flex-direction: row; justify-content: center">
              <el-button icon="search" plain round style="padding: 0 20px" @click="doSearch" />
              <el-button type="primary" @click="onAssignAssets" style="margin: 0 8px 0 24px">
                {{ assignLabel }}
              </el-button>
            </div>
          </template>
        </TableSearchWidget>
      </template>
      <template v-slot:actionBefore>
        <slot name="actionBefore" />
      </template>
    </TableWidget>
    <div
      v-if="!hasData"
      style="display: flex; flex-direction: column; align-items: center; flex: 1">
      <slot name="comment" />
      <div style="display: flex; flex-direction: row">
        <el-button
          class="assign-btn"
          type="primary"
          :icon="Plus"
          plain
          text
          @click="onAssignAssets">
          {{ assignLabel }}
        </el-button>
        <el-button class="assign-btn" plain :icon="Refresh" text @click="refresh"> 刷新 </el-button>
      </div>
    </div>
    <LevelSelectorDialog
      ref="refSelectDlg"
      :load="onLoadAssignAssets"
      :finish-select="onFinishSelect"
      :title="selectTitle"
      :search-forms="searchForms"
      :level-columns="assignColumns"
      :tag="props.tag"
      :mode="'MULTI'"
      :root-item="rootItem"
      :level-mode="props.levelMode"
      :product="getProductCode()"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import TableWidget from '@/widget/TableWidget.vue'
import TableSearchWidget from '@/widget/TableSearchWidget.vue'
import LevelSelectorDialog from '@/views/sop/selector/LevelSelectorDialog.vue'
import { useCurrent } from '@/utils/sop/UseCurrentFunc'
import { msgError, msgInfo } from '@/utils/InfoUtil'
import { runMethod } from '@/utils/DateUtil'
import { useTerminal } from '@/utils/sop/UseTerminal'

const hasData = ref()
const refSearch = ref()
const refSelectDlg = ref()
const refTable = ref()
const clickSearch = ref();

const props = withDefaults(
  defineProps<{
    tag: string
    name: string
    columns: any
    product?: boolean
    defaultTerminal?: string
    levelMode: boolean
    assignColumns: any
    loadAssets?: any
    assignAssets?: any
    loadAssignAssets?: any
  }>(),
  {
    levelMode: false
  }
)

const { current } = useCurrent(props.name)
const { productCode } = useTerminal(props.name)

const currentTerminalCode = ref(productCode())

const tag = computed(() => {
  return props.tag ? props.tag : ''
})

const selectTitle = computed(() => {
  return `分配${props.tag}`
})

const assignLabel = computed(() => {
  return props.tag ? ` 分配${props.tag}` : '分配资源'
})

const rootItem = computed(() => {
  return { id: '', name: `${tag.value}列表` }
})

const onLoadAssets = async (params: any) => {
  let result: any;
  result = await runMethod({
    ...params, productCode: getProductCode(),
  }, async (p: any) => {
    if (props.loadAssets) {
      result = await props.loadAssets(p)
    } else {
      result = {
        code: -1,
        message: '功能未实现'
      }
    }
    return result;
  })

  hasData.value = result != null && result.code === 0 && result.data && result.data.total > 0;
  if (clickSearch.value) {
    hasData.value = true;
  }

  return result
}

const onLoadAssignAssets = async (params: any) => {
  if (props.loadAssignAssets) {
    return await props.loadAssignAssets({
      ...params,
      productCode: getProductCode(),
    })
  }
}

const onTerminalChanged = (val: string) => {
  currentTerminalCode.value = val
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0
})

const searchForms = ref([
  {
    type: 'input',
    name: 'name',
    label: `${tag.value}名称`,
    size: 'default',
    placeholder: `请输入${tag.value}名称`,
    clearable: true,
    defValue: ''
  }
])

const calcSearchForms = () => {
  const params = []
  const hasProduct: boolean = false;//props.product;
  if (hasProduct) {
    params.push({
      type: 'select',
      name: 'productCode',
      label: `产品类型`,
      size: 'default',
      placeholder: `请选择产品类型`,
      clearable: true,
      defValue: 'default',
      minWidth: '120px',
      onChanged: onTerminalChanged,
      options: [
        {
          label: '默认',
          value: 'default'
        },
        {
          label: '小程序',
          value: 'mp'
        },
        {
          label: 'H5应用',
          value: 'h5'
        }
      ]
    })
  }

  params.push(searchForms.value[0])

  return params;
}

const searchParams = ref(calcSearchForms());

const refreshAssets = async () => {
  await refTable.value?.refreshData({
    ...refSearch.value?.getSearchParams(),
    productCode: currentTerminalCode.value
  })
}

const doSearch = async () => {
  clickSearch.value = true;
  await refreshAssets();
}

const onFinishSelect = async (items: any) => {
  if (props.assignAssets) {
    const result = await props.assignAssets(items)
    if (result && result.code === 0) {
      msgInfo(`分配${tag.value}成功！`)
      await refresh()
    } else {
      msgError(`分配${tag.value}失败！`)
    }
  }
}

const updateTitle = () => {
  if (current() && current().name) {
    refSelectDlg.value?.updateTitle(`分配${tag.value}给 ` + current().name)
  } else {
    refSelectDlg.value?.updateTitle(`分配${tag.value}`)
  }
}

const onAssignAssets = () => {
  refSelectDlg.value.select()
  nextTick(() => updateTitle())
}

const refresh = async () => {
  hasData.value = true
  await nextTick(() => refreshAssets())
}

const getProductCode = () => {
  return props.product ? currentTerminalCode.value : productCode()
}

defineExpose({
  refresh,
  getProductCode,
})
</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

.assign-btn {
  margin: 16px 0;
}
</style>
